<template>
  <div ref="chartEl" :style="{ width: width, height: height }"></div>
</template>

<script>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts/core';
import { TooltipComponent, GridComponent, LegendComponent } from 'echarts/components';
import { BarChart, LineChart, PieChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

// 使用命名导入 debounce
import debounce from 'lodash-es/debounce';

export default {
  props: {
    options: {
      type: Object,
      required: true
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    }
  },
  
  setup(props) {
    const chartEl = ref(null);
    let chartInstance = null;
    let resizeObserver = null;

    // 按需注册组件
    echarts.use([
      TooltipComponent,
      GridComponent,
      LegendComponent,
      BarChart,
      LineChart,
      PieChart,
      CanvasRenderer
    ]);

    // 初始化图表
    const initChart = () => {
      if (chartEl.value) {
        chartInstance = echarts.init(chartEl.value);
        chartInstance.setOption(props.options);
      }
    };

    // 响应式调整
    const resizeHandler = () => {
      if (chartInstance) {
        chartInstance.resize();
      }
    };

    // 使用防抖的更新函数
    const updateChart = debounce((newOptions) => {
      if (chartInstance) {
        chartInstance.setOption(newOptions, true);
      }
    }, 300);

    onMounted(() => {
      initChart();
      
      // 使用 ResizeObserver 监听容器大小变化
      if ('ResizeObserver' in window) {
        resizeObserver = new ResizeObserver(resizeHandler);
        if (chartEl.value) {
          resizeObserver.observe(chartEl.value);
        }
      } else {
        // 如果不支持 ResizeObserver，则回退到 window resize 事件
        window.addEventListener('resize', resizeHandler);
      }
    });

    onBeforeUnmount(() => {
      // 移除监听
      if (resizeObserver) {
        resizeObserver.disconnect();
      } else {
        window.removeEventListener('resize', resizeHandler);
      }
      
      // 销毁图表实例
      if (chartInstance) {
        chartInstance.dispose();
        chartInstance = null;
      }
    });

    // 监听选项变化
    watch(() => props.options, (newOptions) => {
      updateChart(newOptions);
    }, { deep: true });

    return {
      chartEl
    };
  }
};
</script>